<!-- 发布、修改项目 -->
<template>
    <page-header-wrapper  @back="() => $router.go(-1)" class="detail">
        <div class='table-page-search-wrapper'>
            <a-card :body-style="{padding: '24px 32px'}" title="基本任务信息" :bordered="false">
                <a-form-model :model="project" ref="ruleForm" :rules="rules" style="margin: 40px auto 0;">
                    <a-form-model-item label="项目名称" prop="projectName" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-input v-model="project.projectName" placeholder="请输入项目名称" allowClear/>
                    </a-form-model-item>
                    <!-- <a-form-model-item label="项目合同编号" prop="contractNum" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-input v-model="project.contractNum" placeholder="请输入项目合同编号" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="项目合同名称" prop="contractName" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-input v-model="project.contractName" placeholder="请输入项目合同名称" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="签署日期" prop="signTime" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-date-picker v-model="project.signTime" valueFormat="YYYY-MM-DD" style="width: 100%"/>
                    </a-form-model-item>
                    <a-form-model-item label="项目合同有效期" prop="contractDate" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-range-picker v-model="project.contractDate" valueFormat="YYYY-MM-DD" style="width: 100%" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="合同金额" prop="cost" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-input v-model="project.cost" :disabled="!isAdd" placeholder="请输入合同金额" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="项目合同" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-upload
                            name="file"
                            @change="handleChange"
                            :before-upload="beforeUpload"
                            :fileList = fileList
                            accept=".pdf,.jpg,.png,.jpeg"
                            :remove="()=>{fileList = []}"
                        >
                            <a-button type="primary"> 上传 </a-button>
                            <p class="ant-upload-text" style="margin-top: 10px">
                                仅支持上传PDF、jpg、png、jpeg格式，文件大小最多20M
                            </p>
                        </a-upload>
                    </a-form-model-item> -->
                    <a-form-model-item label="所属公司" prop="companyId" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-select v-model="project.companyId" :disabled="!isAdd" @change="getCustomer">
                            <a-select-option v-for="item in companyList" :key="item.id" :value="item.id">{{ item.companyName }}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="所属客户" prop="customerId" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-select v-model="project.customerId" :disabled="!isAdd" @change="getContract">
                            <a-select-option v-for="item in customerList" :key="item.id" :value="item.id">{{ item.customerName }}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="项目类型" prop="projectType" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-select v-model="project.projectType" :disabled="!isAdd">
                            <a-select-option v-for="item in projectTypeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="项目描述" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-textarea v-model="project.remark" rows="4" placeholder="请输入项目描述" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="选择合同" prop="contractId" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-select v-model="project.contractId" :disabled="!isAdd" allowClear>
                            <a-select-option v-for="item in contractList" :key="item.id" :value="item.id">{{ item.contractName }}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="合同有效期" prop="date" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
                        <a-range-picker v-model="project.date" valueFormat="YYYY-MM-DD" style="width: 100%" :disabled="!isAdd" allowClear/>
                    </a-form-model-item>
                    <a-form-model-item label="签约前结算" :labelCol="{lg: {span: 5}, sm: {span: 7}}" :wrapperCol="{lg: {span: 10}, sm: {span: 17} }" help="温馨提示：允许“签约前结算”后，加入该项目的人员未签约状态下也允许上传结算单并支付。">
                        <a-radio-group v-model="project.signBeforeSettlement">
                            <a-radio :value="1">开启</a-radio>
                            <a-radio :value="0">关闭</a-radio>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item :wrapperCol="{ span: 15 }" style="text-align: right">
                        <a-button @click="submit" type="primary">提交</a-button>
                    </a-form-model-item>
                </a-form-model>
            </a-card>
        </div>  
    </page-header-wrapper>
</template>

<script>
import { createProject , updateProject } from '@/api/services/project';
import { getCustomerByCompany } from '@/api/services/customer';
import { queryMyCompany } from '@/api/services/company';
import { getContractByCustomer } from '@/api/services/contract';
import { fileUpload } from '@/api/system';
export default {
    data () {
        return {
            form: this.$form.createForm(this),
            isAdd: true,
            project: {
                id: '',
                projectName: '', // 项目名称
                cost: '', // 预估费用
                companyId: undefined, // 公司ID
                customerId: undefined, // 客户ID
                remark: '', // 项目描述
                contractId: undefined, // 合同ID
                projectType: 1, // 项目类型，1：自然人，2：个体户
                contractStartTime: '', // 合同开始时间
                contractEndTime: '', // 合同结束时间
                signBeforeSettlement: 0, // 签约前结算
                projectContract: {
                    contractName: '', // 项目合同名称
                    contractNum: '', // 项目合同编号
                    signTime: '', // 签署日期
                    contractStartTime: '', // 项目合同开始日期
                    contractEndTime: '', // 项目合同结束日期
                    contractUrl: '', // 合同链接
                },
                contractDate: [],
                signTime: '',
                contractNum: '',
                contractName: '',
            },
            rules: {
                projectName: [
                    { required: true, message: '请输入项目名称', trigger: 'blur' },
                ],
                // contractNum: [
                //     { required: true, message: '请输入项目合同编号', trigger: 'blur' },
                // ],
                // contractName: [
                //     { required: true, message: '请输入项目名称', trigger: 'blur' },
                // ],
                // signTime: [
                //     { required: true, message: '请选择合同签署时间', trigger: 'blur' },
                // ],
                // contractDate: [
                //     { required: true, message: '请选择合同时间', trigger: 'blur' },
                // ],
                // cost: [
                //     { required: true, message: '请输入合同金额', trigger: 'blur' },
                //     { pattern: /^[0-9]*$/, message: '请输入正确的合同金额', trigger: 'blur'}
                // ],
                companyId: [{ required: true, message: '请选择所属公司', trigger: 'blur' }],
                customerId: [{ required: true, message: '请选择所属客户', trigger: 'blur' }],
                projectType: [{ required: true, message: '请选择项目类型', trigger: 'blur' }],
                contractId: [{ required: true, message: '请选择合同', trigger: 'blur' }],
                date: [{ required: true, message: '请选择合同时间', trigger: 'blur' }],
            },
            companyList: [], // 公司列表
            customerList: [], // 客户列表
            contractList: [], // 合同列表
            projectTypeList: [
                { id: 1, name: '自然人'}, { id: 2, name: '个体户'}
            ], // 项目类型，
            fileList: [],
        };
    },
    async created(){
        console.log(this.$route.query.project)
        if(this.$route.query.project){
            this.isAdd = false;
            var project = JSON.parse(this.$route.query.project)
            project.date = [project.contractStartTime,project.contractEndTime]
            if(project.projectContract){
                project.contractDate = [project.projectContract.contractStartTime,project.projectContract.contractEndTime];
                project.signTime = JSON.parse(JSON.stringify(project.projectContract.signTime));
                project.contractName = project.projectContract.contractName;
                project.contractNum = project.projectContract.contractNum;
                project.contractUrl = project.projectContract.contractUrl;
            }
            this.project = JSON.parse(JSON.stringify(project));
            console.log(this.project,'project');
        }
        try {
            await this.getCompany();
            if(!this.isAdd){
                await this.getCustomer(this.project.companyId);
                await this.getContract(this.project.customerId);
            }
        } catch (error) {
            this.$notification['error']({
                message: '温馨提示',
                description: error ?? '网络丢失',
                duration: 8
            })
        }
    },
    methods: {
        // 获取用户所有公司列表
        getCompany(){
            let _this = this
            return new Promise((resolve,reject) => {
                queryMyCompany({'pageSize': 99,'pageIndex': 1,})
                .then(res=>{
                    if(res.success){
                        var list = [];
                        for(let i = 0; i < res.data.length; i++){
                            if(res.data[i].realNameStatus == '3'){
                                list.push(res.data[i])
                            }
                        }
                        _this.companyList = list;
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 获取用户所有客户列表
        getCustomer(companyId){
            let _this = this
            if(_this.isAdd){
                _this.project.customerId = undefined
            }   
            return new Promise((resolve,reject) => {
                getCustomerByCompany(companyId)
                .then(res=>{
                    console.log(res,'customerRes')
                    if(res.success){
                        _this.customerList = res.data;
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 根据客户获取已关联的合同列表
        getContract(customerId){
            let _this = this
            if(_this.isAdd){
                _this.project.contractId = undefined
            }
            return new Promise((resolve,reject) => {
                getContractByCustomer(customerId)
                .then(res=>{
                    console.log(res,'customerRes')
                    if(res.success){
                        _this.contractList = res.data;
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 提交添加、修改项目
        submit(){
            let _this = this
            console.log(_this.project.signTime)
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    _this.project.contractStartTime = _this.project.date[0]
                    _this.project.contractEndTime = _this.project.date[1]
                    // _this.project.projectContract.contractName = _this.project.contractName
                    // _this.project.projectContract.contractNum = _this.project.contractNum
                    // _this.project.projectContract.signTime = _this.project.signTime
                    // _this.project.projectContract.contractStartTime = _this.project.contractDate[0]
                    // _this.project.projectContract.contractEndTime = _this.project.contractDate[1]
                    var api = _this.isAdd ? createProject(_this.project) : updateProject(_this.project);
                    api.then(res=>{
                        if(res.success){
                            if(_this.isAdd){
                                _this.$router.push({path: '/servicesProjects/editProject/success', query: {projectId: res.data}})
                            }else{
                                _this.$notification['success']({
                                    message: '温馨提示',
                                    description: '修改成功',
                                    duration: 8
                                })
                                _this.$router.go(-1)
                            }
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        beforeUpload(file) {
            return false;
        },
        handleChange({file,fileList}){
            let _this = this
            const status = file.status;
            if(file.status === 'removed'){
                this.fileList = []
                return
            }
            this.fileList = fileList
            const formData = new FormData();
            formData.append('multipartFile',file)
            fileUpload(formData)
            .then(res=>{
                if(res.success){
                    _this.project.projectContract.contractUrl = res.data
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
    }
}

</script>
<style scoped>

</style>